package zk.tool.handler;

import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import zk.tool.Threads;
import zk.tool.ZKClient;
import zk.tool.model.TreeItemData;
import zk.tool.util.AlertUtil;
import zk.tool.util.TreeCommon;

public class DeleteTreeItemClickHandler extends AbstractTreeContextMenuClickHandler<TreeItemData> {
    private static final Logger log = LoggerFactory.getLogger(DeleteTreeItemClickHandler.class);

    public DeleteTreeItemClickHandler(TreeView<TreeItemData> treeView, ZKClient client) {
        super(treeView, client);
    }

    @Override
    public void handle0(ActionEvent event, TreeItem<TreeItemData> selectedItem) {
        TreeItemData itemData = selectedItem.getValue();
        if (itemData == null) {
            log.info("item data is null");
            return;
        }
        try {
            client.delete(itemData.getPath());
            Threads.TREE_LOAD_THREAD_POOL.execute(() -> {
                try {
                    TreeItem<TreeItemData> parent = selectedItem.getParent();
                    if (parent != null) {
                        TreeCommon.refreshChildren(client, parent);
                    }
                } catch (Exception e) {
                    log.error("refresh path [" + itemData.getPath() + "] exception", e);
                    Platform.runLater(() -> {
                        AlertUtil.exception("刷新子节点异常，请尝试手动刷新", e);
                    });
                }
            });
        } catch (Exception e) {
            log.error("delete path: [" + itemData.getPath() + "] error.", e);
            AlertUtil.exception("删除节点异常", e);
        }
    }
}
